package com.barbeque.mall.service.wx;

import com.barbeque.mall.bean.BasePageInfo;
import com.barbeque.mall.bean.param.CommonData;
import com.barbeque.mall.bean.user.MarketCollect;
import com.barbeque.mall.bean.user.MarketCollectExample;
import com.barbeque.mall.bean.user.MarketUser;
import com.barbeque.mall.bean.wx.collect.ListOfCollectVo;
import com.barbeque.mall.mapper.MarketCollectMapper;
import com.barbeque.mall.util.UserInfoUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author ycc
 * @date 2022/07/20 13:56:58
 */
@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    MarketCollectMapper collectMapper;

    //收藏列表
    @Override
    public CommonData<ListOfCollectVo> list(BasePageInfo pageInfo, Integer type) {
        PageHelper.startPage(pageInfo.getPage(),pageInfo.getLimit());
        //获取用户信息
        int userId = UserInfoUtils.getUserId();
        //TODO:根据id查询收藏商品信息
        List<ListOfCollectVo> list = collectMapper.selectCollectsByConditon(userId,type);
        PageInfo<ListOfCollectVo> info = new PageInfo<>(list);

        return CommonData.data(info);
    }

    //添加或取消收藏
    @Override
    public int addordelete(MarketCollect collect) {
        //获取用户信息
        int userId = UserInfoUtils.getUserId();
        //获取收藏商品信息
        MarketCollectExample collectExample = new MarketCollectExample();
        MarketCollectExample.Criteria criteria = collectExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andValueIdEqualTo(collect.getValueId());
        criteria.andTypeEqualTo(collect.getType());
        List<MarketCollect> collects = collectMapper.selectByExample(collectExample);

        //TODO：判断该用户的收藏中是否收藏该商品，没有则插入数据
        if (collects.size()<=0) {
            //没有收藏，直接插入
            collect.setUserId(userId);
            collect.setAddTime(new Date());
            collect.setDeleted(false);
            return collectMapper.insertSelective(collect);
        }
        //有则修改收藏的删除状态位
        Boolean deleted = collects.get(0).getDeleted();
        if (deleted) {
            collect.setDeleted(false);
        }else {
            collect.setDeleted(true);
        }
        collect.setUpdateTime(new Date());
        return collectMapper.updateByExampleSelective(collect,collectExample);
    }
}
